#include "redis.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

// Redis 连接上下文
redisContext *redis_conn;

/**
 * 初始化Redis连接
 */
void init_redis() {
    redis_conn = redisConnect("127.0.0.1", 6379);
    if (redis_conn != NULL && redis_conn->err) {
        fprintf(stderr, "Redis connection error: %s\n", redis_conn->errstr);
        exit(EXIT_FAILURE);
    }
}

/**
 * 验证用户的用户名和密码
 * 
 * @param username 用户名
 * @param password 密码
 * @return 认证成功返回1，失败返回0
 */
int authenticate_user(const char *username, const char *password) {
    // 先从 Redis 缓存中查询用户信息
    redisReply *reply = (redisReply *)redisCommand(redis_conn, "GET %s", username);
    if (reply == NULL || reply->type == REDIS_REPLY_NIL) {
        // Redis 中不存在缓存，从 MySQL 中查询
        printf("User not found in Redis, querying MySQL...\n");
        char query[256];
        sprintf(query, "SELECT * FROM users WHERE username='%s' AND password='%s'", username, password);
        printf("Executing query: %s\n", query);
        if (mysql_query(conn, query)) {
            fprintf(stderr, "SELECT error: %s\n", mysql_error(conn));
            return 0;
        }

        MYSQL_RES *res = mysql_store_result(conn);
        if (res == NULL) {
            fprintf(stderr, "mysql_store_result() failed: %s\n", mysql_error(conn));
            return 0;
        }

        int num_rows = mysql_num_rows(res);
        mysql_free_result(res);

        // 将查询结果存入 Redis 缓存
        if (num_rows > 0) {
            redisReply *set_reply = (redisReply *)redisCommand(redis_conn, "SET %s %s", username, "authenticated");
            freeReplyObject(set_reply);
        }

        printf("Number of rows from MySQL: %d\n", num_rows);
        return num_rows > 0;
    } else {
        // 从 Redis 缓存中获取结果
        int authenticated = (strcmp(reply->str, "authenticated") == 0);
        printf("User found in Redis, authenticated: %d\n", authenticated);
        freeReplyObject(reply);
        return authenticated;
    }
}


/**
 * 刷新Redis缓存
 * 
 * @param username 用户名
 */
void refresh_redis_cache(const char *username) {
    redisReply *set_reply = (redisReply *)redisCommand(redis_conn, "SET %s %s EX 600", username, "authenticated");
    if (set_reply == NULL) {
        fprintf(stderr, "Failed to update Redis cache for user %s\n", username);
    } else {
        freeReplyObject(set_reply);
        printf("Redis cache for user %s refreshed.\n", username);
    }
}

/**
 * 批量刷新多个用户的Redis缓存
 * 
 * @param usernames 用户名数组
 * @param num_users 用户数量
 */
void refresh_multiple_users_redis_cache(const char **usernames, int num_users) {
    for (int i = 0; i < num_users; ++i) {
        refresh_redis_cache(usernames[i]);
    }
}